import api from '../../lib/httpapi'
const log = console.log

const range = count => Array(count).fill(0).map((v, i) => v = i)

/**
 * 停车位状态数据结构
 * {
    no: Number,
    cam: Number,
    pno: Number
    status: "空闲"
    }
 */
const parkingMonitor = {
    namespaced: true,
    state: {
        parkingItems: [],
        cameras: [],
    },

    mutations: {
        initParkingStatus(state, data) {
            try {
                state.parkingItems = state.parkingItems.concat(data)
                state.parkingItems = state.parkingItems.map((v, i) => v.no = i)
            } catch (err) {
                console.error(err)
            }
        },

        updateParkingStatus(state, data) {
            try {
                for (var item of data) {
                    state.parkingItems = state.parkingItems.map((v, i) => v.cam == item.cam && v.pno == item.pno ? (v.status = item.status) : v)
                }
            } catch (err) {
                console.error(err)
            }
        },

        setCamera(state, data) {
            if (data.length > 0) {
                data.map(v => {
                    if (state.cameras.indexOf(v) == -1)
                        state.cameras.push(v)
                })
            }
        },

        // updateCamera(state, data) {
        //     if (typeof data == 'string')
        //         data = JSON.parse(data)
        //     state.cameras[data.no] = data.frame
        // }
    },
    actions: {
        async getParkingStatus({ commit }) {
            try {
                let res = await api.load_parking_status()
                if (res.status == 200)
                    commit('insertParkingStatusItems', res.data)
                else
                    return false
            } catch (err) {
                log(err)
                return false
            }
        }
    }
}

export default parkingMonitor